package com.bookmanager.www.controller;

import cn.hutool.core.util.IdUtil;
import com.bookmanager.www.common.DTO.UserDTO;
import com.bookmanager.www.common.utils.CommonsUtils;
import com.bookmanager.www.common.utils.LoginUserUtils;
import com.bookmanager.www.common.utils.Result;
import com.bookmanager.www.entity.FlUser;
import com.bookmanager.www.entity.LoginDetail;
import com.bookmanager.www.mapper.FlUserMapper;
import com.bookmanager.www.service.FlUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2021/10/02/14:19
 * @Description:
 */
@RestController
@RequestMapping("/fl-registerOrLogin")
@Slf4j
@Api(tags = "注册登录管理")
public class LoginAndRegisterController {

    @Resource
    FlUserService flUserService;
    

    @Resource
    FlUserMapper flUserMapper;

    @Resource
    RabbitTemplate rabbitTemplate;



    @PostMapping("/sendUserIpDetail")
    @ApiOperation(value = "获取用户登录ip信息")
    Result sendUserIpDetail(@RequestParam("ip") String ip,@RequestParam("userId")String userId)
    {
        String ipDetail = LoginUserUtils.getUserDetail(ip);
        LocalDateTime now = LocalDateTime.now();
        String detailId = IdUtil.getSnowflake().nextIdStr();
        if(LoginUserUtils.getUserDetail(ip).equals("error"))
        {
            return Result.fail("该ip格式错误！","");
        }
        int insert = flUserMapper.insertUserLoginDetail(detailId,userId,ipDetail,now,ip);
        if(insert!=0)
        {
            LoginDetail loginDetail = flUserMapper.selectLoginDetail(detailId);
            return Result.succ("当前用户信息保存成功！！",loginDetail);
        }
       return Result.fail("未知错误！","");
    }

    @PostMapping("/loginUserByPhoneCode")
    @ApiOperation(value="手机号验证码登录",notes="传入手机号即可")
    Result loginUserByPhoneCode(@RequestParam("phoneNum")String phoneNum, HttpServletResponse response)
    {
        FlUser flUser = flUserMapper.selectUserByPhoneNum(phoneNum);
        if(flUserMapper.getUserStatus(flUser.getUserId())!=0)
        {
            return Result.fail("该账号已被禁封！！！！","");
        }
        return LoginUserUtils.login(flUser,response);
    }

    @PostMapping("/registerByEmail")
    @ApiOperation(value="邮箱注册",notes="传入邮箱号和密码即可")
    /**
     * 邮箱登录逻辑：
     * 1： 判断该邮箱是否已经注册过 SearchUserByEmail
     * 2： 点击发送验证码即访问生成验证码接口 并存入Redis 设置5分钟过期 CodeController
     * 3： 用户输入验证码 实时显示验证码是否正确 CodeController
     * 4：让用户输入密码注册流程完成！
     */
    Result registerByEmail(@RequestParam("email")String email,@RequestParam("password")String password)
    {
        //新增邮箱是否重复
        if(flUserMapper.selectUserByEmail(email)!=null)
        {
            return Result.fail("注册失败 原因：邮箱已存在！！","");
        }

        int insertUser = flUserService.registerUserByEmail(email,password);
        if (insertUser!=0)
        {
            FlUser flUser =flUserMapper.selectUserByEmail(email);
            //这里添加邮箱发送推送账号密码短信
            rabbitTemplate.convertAndSend("sendEmail","",email+" "+password);
            return Result.succ("注册成功",flUser);
        }
        return Result.fail("注册失败 原因：插入数据库失败","");

    }

    @PostMapping("/registerByPhoneNum")
    @ApiOperation(value="手机号注册",notes="传入手机号和密码即可")
    Result registerByPhoneNum(@RequestParam("phoneNum")String phoneNum,@RequestParam("password")String password)
    {
        //新增手机号是否重复
        if(flUserMapper.selectUserByPhoneNum(phoneNum)!=null)
        {
            return Result.fail("注册失败 原因：用户手机号已注册！！","");
        }
        int insertUser=flUserService.registerByPhoneNum(phoneNum,password);
        if (insertUser!=0)
        {
            //这里添加手机号发送推送账号密码短信
            FlUser flUser =flUserMapper.selectUserByPhoneNum(phoneNum);
            //这里短信发送成功与否与业务逻辑无关 所以可以分割开
            rabbitTemplate.convertAndSend("sendPhoneCode",phoneNum+" "+password);

            return Result.succ("注册成功",flUser);
        }

        return Result.fail("注册失败 原因：插入数据库失败","");
    }

    @PostMapping("/registerUser")
    @ApiOperation(value = "用户注册",notes = "传入用户名 以及密码 username password")
    Result registerUser(@RequestBody @Validated UserDTO userDTO){
        //新增验证用户名是否重复
        if(flUserMapper.selectUserByUsername(userDTO.getUsername())!=null)
        {
            return Result.fail("注册失败 原因：该用户名已存在！！！","");
        }
        int insertUser = flUserService.registerUser(userDTO.getUsername(),userDTO.getPassword());
        if (insertUser!=0)
        {
            FlUser flUser =flUserService.selectUserByUsername(userDTO.getUsername());


            return Result.succ("注册成功",flUser);
        }
        return Result.fail("注册失败 原因：插入数据库失败","");
    }


    @PostMapping("/loginUser")
    @ApiOperation(value = "用户手机号邮箱用户名登录",notes = "传入用户名或者邮箱或者手机号 以及密码 username password")
    Result loginUser(@RequestBody UserDTO userDTO, HttpServletResponse response){


        if(userDTO.getUsername().contains("@"))
        {
            //邮箱登录
            FlUser flUser =flUserService.selectUserByEmailAndPassword(userDTO.getUsername(),userDTO.getPassword());
            if(flUser==null)
            {
                return Result.fail("该账户不存在","");
            }
            if(flUserMapper.getUserStatus(flUser.getUserId())!=0)
            {
                return Result.fail("该账号已被禁封！！！！","");
            }
            return LoginUserUtils.login(flUser,response);
        }
        if(CommonsUtils.phoneRegexCheck(userDTO.getUsername()))
        {
            //手机号登录
            FlUser flUser =flUserService.selectUserByPhoneNumAndPassword(userDTO.getUsername(),userDTO.getPassword());
            if(flUser==null)
            {
                return Result.fail("该账户不存在","");
            }
            if(flUserMapper.getUserStatus(flUser.getUserId())!=0)
            {
                return Result.fail("该账号已被禁封！！！！","");
            }
            return LoginUserUtils.login(flUser,response);
        }
        //账号登录
        FlUser flUser = flUserService.selectUserByUsernameAndPassword(userDTO.getUsername(),userDTO.getPassword());
        if(flUser==null)
        {
            return Result.fail("该账户不存在","");
        }
        if(flUserMapper.getUserStatus(flUser.getUserId())!=0)
        {
            return Result.fail("该账号已被禁封！！！！","");
        }
        return LoginUserUtils.login(flUser,response);
    }

    @RequiresAuthentication
    @GetMapping("/logoutUser")
    @ApiOperation(value = "用户登出",notes = "直接访问即可 会清除token")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("",null);
    }

}
